<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模拟axios请求</title>
</head>
<body>
    <script>
        //1.声明Axios对象
        function Axios(config){
            this.config=config;
        }

        //2.为Axios的原型上添加request方法
        Axios.prototype.request= function(config){
            let promise= Promise.resolve(config);
            let chains= [dispatchRequest,undefined];
            let result= promise.then(chains[0],chains[1]);
           return result;
        }

        //3. dispatchRequest函数，会在request中调用
        function dispatchRequest(config){
           return  xhrAdapter(config).then(response=>{
                    return response;
            },error=>{
                throw error;
            })
        }

        //4. adapter 适配器， 主要用来ajax请求的
        function xhrAdapter(config){
            return new Promise((resolve,reject)=>{
                //发送 AJAX 请求
                let xhr = new XMLHttpRequest();
                //初始化
                xhr.open(config.method, config.url);
                //发送
                xhr.send();
                xhr.onreadystatechange=function(){
                    if(xhr.readyState === 4){
                        //判断成功的条件
                        if(xhr.status >= 200 && xhr.status < 300){
                            //成功的状态
                            resolve({
                                //配置对象
                                config: config,
                                //响应体
                                data: xhr.response,
                                //响应头
                                headers: xhr.getAllResponseHeaders(), //字符串  parseHeaders
                                // xhr 请求对象
                                request: xhr,
                                //响应状态码
                                status: xhr.status,
                                //响应状态字符串
                                statusText: xhr.statusText
                            });
                        }else{
                            //失败的状态
                            reject(new Error('请求失败 失败的状态码为' + xhr.status));
                        }
                    }
                }
            })
        }

        //5. 使用自定义的Axios
        let axios = Axios.prototype.request.bind(null);
        axios({
            method:'GET',
            url:'https://api.uomg.com/api/rand.qinghua'
        }).then(response => {
            console.log(response);
            console.log("data",response.data);
        });

    </script>
</body>
</html>